﻿using PdfiumViewer;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Drawing.Text;
using System.IO;

namespace BatchPrint.Converter;

public class PdfToImageConverter : IImageConverter
{
    public Task<DImage> Convert(string filePath)
    {
        using var pdfDoc = PdfDocument.Load(filePath);
        var stream = ConvertToStream(pdfDoc, 0, 600);
        var image = DImage.FromStream(stream);
        return Task.FromResult(image);
    }

    public Stream ConvertToStream(PdfDocument document, int pageNumber, int dpi = 300)
    {
        //// 增加DPI和图片尺寸
        var page = document.PageSizes[pageNumber];
        //var width = (int)(page.Width * dpi / 72.0);
        //var height = (int)(page.Height * dpi / 72.0);

        //using var bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb);
        //bitmap.SetResolution(dpi, dpi);

        //using var graphics = Graphics.FromImage(bitmap);
        //// 设置高质量绘图
        //graphics.CompositingQuality = CompositingQuality.HighQuality;
        //graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
        //graphics.SmoothingMode = SmoothingMode.HighQuality;
        //graphics.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;

        //// 使用白色背景
        //graphics.Clear(Color.White);

        //// 渲染PDF页面
        //document.Render(pageNumber, graphics, 0, 0, new Rectangle(0, 0, width, height), true);

        //// 使用高质量压缩
        //return CompressImageWithQuality(bitmap);

        int width = System.Convert.ToInt32(page.Width) * 2;
        int height = System.Convert.ToInt32(page.Height) * 2;
        using var image = document.Render(pageNumber, width, height, 500, 500, PdfRenderFlags.ForPrinting);
        var ms = new MemoryStream();
        image.Save(ms, ImageFormat.Png);
        return ms;
    }

    private static byte[] CompressImageWithQuality(Bitmap bitmap)
    {
        using var ms = new MemoryStream();

        // 使用高质量编码器设置
        var encoderParameters = new EncoderParameters(1);
        encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 95L);

        var codec = ImageCodecInfo.GetImageEncoders()
            .First(c => c.FormatID == ImageFormat.Png.Guid);

        bitmap.Save(ms, codec, encoderParameters);
        return ms.ToArray();
    }
}
